package com.cskaoyan.service.goods;

import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.model.vo.PageListVo;
import com.cskaoyan.model.vo.goods.wxgoods.CommentEntity;
import com.cskaoyan.model.vo.goods.wxgoods.SpecificationListEntity;
import com.cskaoyan.model.vo.goods.wxgoods.WxGoodsDetailListVo;
import com.cskaoyan.model.vo.goods.wxgoods.WxRelatedVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import com.cskaoyan.bean.*;
import com.cskaoyan.mapper.MallCategoryMapper;
import com.cskaoyan.mapper.MallGoodsMapper;
import com.cskaoyan.mapper.MallSearchHistoryMapper;
import com.cskaoyan.model.bo.PageBo;
import com.cskaoyan.model.vo.goods.wxgoods.WxGoodsListBySearchVo;
import com.cskaoyan.model.vo.goods.wxgoods.WxGoodsListVo;
import com.cskaoyan.model.vo.order.WxGoodsCategoryVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import com.cskaoyan.bean.MallCategory;
import com.cskaoyan.bean.MallCategoryExample;
import com.cskaoyan.bean.MallGoods;
import com.cskaoyan.bean.MallGoodsExample;
import com.cskaoyan.mapper.MallSystemMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import java.util.Date;
import java.util.List;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * @program: project-market
 * @description:
 * @author: zhijie
 * @create: 2021-12-04 19:09
 **/
@Service
public class WxGoodsServiceImpl implements WxGoodsService {

    @Autowired
    MallGoodsMapper goodsMapper;
    @Autowired
    MallGoodsSpecificationMapper goodsSpecificationMapper;
    @Autowired
    MallIssueMapper issueMapper;
    @Autowired
    MallCommentMapper commentMapper;
    @Autowired
    MallGoodsAttributeMapper goodsAttributeMapper;
    @Autowired
    MallBrandMapper brandMapper;
    @Autowired
    MallGoodsProductMapper goodsProductMapper;
    @Autowired
    MallCollectMapper collectMapper;

    @Autowired
    MallSystemMapper systemMapper;
    @Autowired
    MallCategoryMapper categoryMapper;

    @Override
    public PageListVo relate(Integer id) {

        // 根据商品id获取它的category_id，
        MallGoods mallGoods = goodsMapper.selectByPrimaryKey(id);
        Integer categoryId = mallGoods.getCategoryId();

        // 根据category_id查询相似数据
        List<WxRelatedVo> goodsList = goodsMapper.selectByCategoryId(categoryId);


        PageInfo info = new PageInfo(goodsList);
        PageListVo vo = new PageListVo();
        vo.setTotal((long) goodsList.size());
        vo.setLimit(6);
        vo.setPage(info.getPageSize());
        vo.setPages(info.getPages());
        vo.setList(info.getList());

        return vo;

    }


    @Override
    public WxGoodsDetailListVo detail(Integer id, Integer uid) {

        // 根据goodsId查goodsInfo
        MallGoods mallGoods = goodsMapper.selectByPrimaryKey(id);


        // 根据goodsId查goodsSpecification
        MallGoodsSpecificationExample goodsSpecificationExample = new MallGoodsSpecificationExample();
        goodsSpecificationExample.createCriteria().andGoodsIdEqualTo(id);
        List<MallGoodsSpecification> goodsSpecifications = goodsSpecificationMapper.selectByExample(goodsSpecificationExample);

        // 筛选出所有的Specification
        List<String> specList = goodsSpecifications.stream().map(s -> s.getSpecification()).distinct().collect(Collectors.toList());

        ArrayList<SpecificationListEntity> specificationListEntities = new ArrayList<>();

        for (String spec : specList) {
            List<MallGoodsSpecification> goodsSpecifications1 = goodsSpecifications.stream().filter(s -> s.getSpecification().equals(spec)).collect(Collectors.toList()
            );
            SpecificationListEntity specificationListEntity1 = new SpecificationListEntity();
            specificationListEntity1.setName(spec);
            specificationListEntity1.setValueList(goodsSpecifications1);
            specificationListEntities.add(specificationListEntity1);
        }


        // 查issue
        MallIssueExample mallIssueExample = new MallIssueExample();
        List<MallIssue> mallIssues = issueMapper.selectByExample(mallIssueExample);


        // 当前用户是否已经收藏当前id
        int userHasCollect = 0;
        if (uid != null) {
            // 用户登录了，查一下是否有被收藏
            MallCollectExample collectExample = new MallCollectExample();
            collectExample.createCriteria().andUserIdEqualTo(uid).andValueIdEqualTo(id).andDeletedEqualTo(false);
            List<MallCollect> mallCollects = collectMapper.selectByExample(collectExample);
            // 如果收藏表中存在数据，说明被收藏，否则没有
            if (mallCollects.size() > 0) userHasCollect = 1;
        }


        // 根据goodsId查询评论
        MallCommentExample commentExample = new MallCommentExample();
        commentExample.createCriteria().andValueIdEqualTo(id);
        List<MallComment> mallComments = commentMapper.selectByExample(commentExample);
        CommentEntity commentEntity = new CommentEntity();
        commentEntity.setCount(mallComments.size());
        commentEntity.setData(mallComments);

        // 查询goodsId查询Attribute

        MallGoodsAttributeExample goodsAttributeExample = new MallGoodsAttributeExample();
        goodsAttributeExample.createCriteria().andGoodsIdEqualTo(id);
        List<MallGoodsAttribute> mallGoodsAttributes = goodsAttributeMapper.selectByExample(goodsAttributeExample);

        // 查询brand
        Integer brandId = mallGoods.getBrandId();
        MallBrand mallBrand = brandMapper.selectByPrimaryKey(brandId);

        // 根据goodsId查询productList
        MallGoodsProductExample goodsProductExample = new MallGoodsProductExample();
        goodsProductExample.createCriteria().andGoodsIdEqualTo(id);
        List<MallGoodsProduct> mallGoodsProducts = goodsProductMapper.selectByExample(goodsProductExample);


        WxGoodsDetailListVo vo = new WxGoodsDetailListVo();
        vo.setSpecificationList(specificationListEntities);
        vo.setGroupon(null);
        vo.setIssue(mallIssues);
        vo.setUserHasCollect(userHasCollect);
        vo.setShareImage("");
        vo.setComment(commentEntity);
        vo.setAttribute(mallGoodsAttributes);
        vo.setBrand(mallBrand);
        vo.setInfo(mallGoods);
        vo.setProductList(mallGoodsProducts);
        return vo;
    }


    @Autowired
    MallGoodsMapper mallGoodsMapper;
    @Autowired
    MallSearchHistoryMapper searchHistoryMapper;
    @Autowired
    MallCategoryMapper mallCategoryMapper;

    @Override
    public WxGoodsCategoryVo goodsCategory(Integer id) {

        //判断传入的是当前类目id是一级还是二级（L2）
        WxGoodsCategoryVo wxGoodsCategoryVo = new WxGoodsCategoryVo();
        MallCategoryExample example4 = new MallCategoryExample();
        example4.createCriteria().andIdEqualTo(id);
        List<MallCategory> mallCategories1 = mallCategoryMapper.selectByExample(example4);
        Integer pid = mallCategories1.get(0).getPid();
        //传入的是一级类目
        if (pid == 0) {
            //查找当前类目（L1）
            MallCategoryExample example1 = new MallCategoryExample();
            example1.createCriteria().andPidEqualTo(id);
            List<MallCategory> mallCategories = mallCategoryMapper.selectByExample(example1);
            MallCategory currentCategory = mallCategories.get(0);
            wxGoodsCategoryVo.setCurrentCategory(currentCategory);

            //查找其父id的所有子类（L2）,获取pid
            MallCategoryExample example2 = new MallCategoryExample();
            example2.createCriteria().andPidEqualTo(currentCategory.getPid());
            List<MallCategory> brotherCategory = mallCategoryMapper.selectByExample(example2);
            wxGoodsCategoryVo.setBrotherCategory(brotherCategory);

            //查找其父类目（L1）
            MallCategory parentCategory = mallCategoryMapper.selectByPrimaryKey(currentCategory.getPid());
            wxGoodsCategoryVo.setParentCategory(parentCategory);

        } else {//传入的是二级类目
            //查找当前类目（L2）
            MallCategoryExample example1 = new MallCategoryExample();
            example1.createCriteria().andIdEqualTo(id);
            List<MallCategory> mallCategories = mallCategoryMapper.selectByExample(example1);
            MallCategory currentCategory = mallCategories.get(0);
            wxGoodsCategoryVo.setCurrentCategory(currentCategory);


            //查找其父id的所有子类（L2）,获取pid
            MallCategoryExample example2 = new MallCategoryExample();
            example2.createCriteria().andPidEqualTo(currentCategory.getPid());
            List<MallCategory> brotherCategory = mallCategoryMapper.selectByExample(example2);
            wxGoodsCategoryVo.setBrotherCategory(brotherCategory);


            //查找其父类目（L1）
            MallCategory parentCategory = mallCategoryMapper.selectByPrimaryKey(currentCategory.getPid());
            wxGoodsCategoryVo.setParentCategory(parentCategory);
        }
        return wxGoodsCategoryVo;
    }

    @Override
    public WxGoodsListVo wxGoodsList(Integer categoryId, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        MallGoodsExample example = new MallGoodsExample();
        example.setOrderByClause("sort_order");
        example.createCriteria().andCategoryIdEqualTo(categoryId);
        List<MallGoods> mallGoods = mallGoodsMapper.selectByExample(example);
        PageInfo<MallGoods> info = new PageInfo<>(mallGoods);
        WxGoodsListVo vo = new WxGoodsListVo();
        vo.setLimit(limit);
        vo.setPage(page);
        vo.setPages(info.getPages());
        vo.setTotal(info.getTotal());
        vo.setList(mallGoods);

        return vo;
    }

    @Override
    public WxGoodsListBySearchVo wxGoodsListBySearch(String keyword, Integer categoryId, PageBo pageBo, Integer id) {
//        List<Integer> list = mallGoodsMapper.selectCategortId(keyword);
        //id不为Null,插入新的搜索历史

        PageHelper.startPage(pageBo.getPage(), pageBo.getLimit());
        if (id != null) {
            MallSearchHistory searchHistory = new MallSearchHistory();
            searchHistory.setUserId(id);
            searchHistory.setDeleted(false);
            searchHistory.setUpdateTime(new Date());
            searchHistory.setAddTime(new Date());
            searchHistory.setFrom("app");
            searchHistory.setKeyword(keyword);
            searchHistoryMapper.insertSelective(searchHistory);
        }
        MallGoodsExample goodsExample = new MallGoodsExample();
        goodsExample.createCriteria().andNameLike("%" + keyword + "%");
        goodsExample.setOrderByClause(pageBo.getSort() + " " + pageBo.getOrder());
        List<MallGoods> mallGoods = mallGoodsMapper.selectByExample(goodsExample);
        if (mallGoods.size() == 0) {
            WxGoodsListBySearchVo vo = new WxGoodsListBySearchVo();
            vo.setLimit(pageBo.getLimit());
            vo.setPage(pageBo.getPage());
            return vo;
        }
        PageInfo<MallGoods> info = new PageInfo<>(mallGoods);
        //取出list中的categoryId ,去重
        List<Integer> list = mallGoods.stream().map(s -> s.getCategoryId()).distinct().collect(Collectors.toList());
        MallCategoryExample example = new MallCategoryExample();
        example.createCriteria().andIdIn(list);
        List<MallCategory> mallCategories = mallCategoryMapper.selectByExample(example);

        WxGoodsListBySearchVo vo = new WxGoodsListBySearchVo();
        vo.setFilterCategoryList(mallCategories);
        vo.setLimit(pageBo.getLimit());
        vo.setList(mallGoods);
        vo.setPage(pageBo.getPage());
        vo.setTotal(info.getTotal());
        vo.setPages(info.getPages());
        return vo;
    }


    //查询商品数量
    @Override
    public int wxGoodsCount() {
        int categoryLimit = Integer.parseInt(systemMapper.selectByPrimaryKey(15).getKeyValue());
        PageHelper.startPage(1, categoryLimit);
        MallCategoryExample homeIndexCategoryExample = new MallCategoryExample();
        MallCategoryExample.Criteria categoryExampleCriteria = homeIndexCategoryExample.createCriteria();
        categoryExampleCriteria.andDeletedEqualTo(false);
        categoryExampleCriteria.andPidEqualTo(0);
//        homeIndexCategoryExample.setOrderByClause("sort_order" + " " + "desc");
        List<MallCategory> categoryList = categoryMapper.selectByExample(homeIndexCategoryExample);
        int count = 0;

        for (MallCategory category : categoryList) {
            MallCategoryExample floorGoodsCategoryExample = new MallCategoryExample();
            floorGoodsCategoryExample.createCriteria().andDeletedEqualTo(false).andPidEqualTo(category.getId());
//            floorGoodsCategoryExample.setOrderByClause("sort_order" + " " + "desc");

            List<MallCategory> mallCategories = categoryMapper.selectByExample(floorGoodsCategoryExample);
            List<Integer> integerList = mallCategories.stream().map(s -> s.getId()).collect(Collectors.toList());
            int floorGoodsLimit = Integer.parseInt(systemMapper.selectByPrimaryKey(12).getKeyValue());
            PageHelper.startPage(1, floorGoodsLimit);
//            List<MallGoods> floorGoodsList=goodsMapper.selectFloorGoods(categoryL2);
            MallGoodsExample goodsExample = new MallGoodsExample();
//            goodsExample.setOrderByClause("sort_order" + " " + "desc");
            goodsExample.createCriteria().andDeletedEqualTo(false).andCategoryIdIn(integerList).andIsOnSaleEqualTo(true);
            int size = goodsMapper.selectByExample(goodsExample).size();
            count += size;
        }
        return count;
    }

    @Override
    public WxGoodsListBySearchVo wxBrandId(Integer brandId, PageBo pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getLimit());
        MallGoodsExample example = new MallGoodsExample();
        example.createCriteria().andBrandIdEqualTo(brandId);
        List<MallGoods> mallGoods = mallGoodsMapper.selectByExample(example);
        PageInfo<MallGoods> info = new PageInfo<>(mallGoods);
        WxGoodsListBySearchVo vo = new WxGoodsListBySearchVo();
        vo.setTotal(info.getTotal());
        vo.setPage(pageBo.getPage());
        vo.setPages(info.getPages());
        vo.setLimit(pageBo.getLimit());
        vo.setList(mallGoods);
        if (mallGoods.size() == 0) {
            return vo;
        }
        List<Integer> categoryId = mallGoods.stream().map(s -> s.getCategoryId()).distinct().collect(Collectors.toList());
        MallCategoryExample example1 = new MallCategoryExample();
        example1.createCriteria().andIdIn(categoryId);
        List<MallCategory> mallCategories = mallCategoryMapper.selectByExample(example1);
        vo.setFilterCategoryList(mallCategories);
        return vo;
    }


}
